(function() {
	var $optimizeForm = $('#optimize-form');
	var $oldTitle = $('span.title', $optimizeForm);
	var $newTitle = $('td.title input.new-title', $optimizeForm);
	
	$( "div.tabs", $optimizeForm ).tabs({
		cache: true
	});
	
	function updateTip($input)
	{
		var title = $input.val();
		var length = window.utils.bytesLength(title);
		var left = 30 - length/2;
		$('div.tip span.left-chars', $optimizeForm).html(left);
		if (left < 0)
		{
			$input.addClass('err');
		}
		else
		{
			$input.removeClass('err');
		}
	}
	
	$newTitle.focus(function(){
		updateTip($(this));
	}).keyup(function(){
		updateTip($(this));
	});
	
	$('a.clear-title', $optimizeForm).click(function(){
		$newTitle.val('');
		$newTitle.focus();
		return false;
	});
	
	$('a.delete-space', $optimizeForm).click(function(){
		var s = $newTitle.val();
		s = s.replace(/ /g, '');
		$newTitle.val(s);
		$newTitle.focus();
		return false;
	});
	
	$newTitle.focus();
	
	function filter($input)
	{
		var numIid = $optimizeForm.attr('numIid');
		var coreWord = $input.val();
		coreWord = coreWord || $('div.keywords', $optimizeForm).attr('defaultCoreWord');
		$.ajax({
			url: 'filter-keywords',
			data: {
				numIid: numIid,
				coreWord: coreWord
			},
			type: 'POST',
			success: function(data){
				$('div.keywords', $optimizeForm).html(data);
			}
		});
	}
	
	$('input.core-word').keypress(function(event){
		if (event.which === 13)
		{
			filter($(this));
		}
	});
	
	$('button.filter', $optimizeForm).button().click(function(){
		filter($('input.core-word'));
		return false;
	});
	
	$('div#prop-words a.keyword', $optimizeForm).click(function(){
		var $newTitle = $('input.new-title', $optimizeForm);
		var title = $newTitle.val();
		title += $(this).text();
		$newTitle.val(title);
		$newTitle.focus();
		return false;
	});
	
	$('button.diagnose', $optimizeForm).click(function(){
		var $result = $('tr.diagnose td.result', $optimizeForm);
		$result.html('<img src="images/loading-small.gif"/>');
		var numIid = $optimizeForm.attr('numIid');
		var title = $newTitle.val();
		$.ajax({
			url: 'diagnose',
			data: {
				numIid: numIid,
				title: title
			},
			type: 'POST',
			success: function(data){
				$result.html(data);
			}
		});
	});
	
	$('a.core-word', $optimizeForm).click(function(){
		var keyword = $(this).text();
		$('input.core-word', $optimizeForm).val(keyword);
		$('button.filter', $optimizeForm).click();
		return false;
	});
})();